package baseclass.b_stackQueue;

/**
 * @date 2020/2/27 17:31
 */
public class Code02_ArrayQueue {
    //表示下一个可以插入的位置
    private int tail;
    //表示下一个可以出队的位置
    private int head;
    private int size;
    private int capacity;

    private int[] queue;

    public Code02_ArrayQueue(int capacity) {
        this.capacity = capacity;
        queue = new int[capacity];
        size = 0;
        head = 0;
        tail = 0;
    }

    public void offer(int e) {
        if (size == capacity) throw new RuntimeException("full");
        queue[tail++] = e;
        //计算tail,如果tail刚好走到最后一个位置，tail+1就是capacity，就重置到0
        tail = tail % capacity;
        size++;
    }

    public int poll() {
        if (size <= 0) throw new RuntimeException("empty");
        int res = queue[head++];
        head = head % capacity;
        size--;
        return res;
    }

    public int getSize() {
        return size;
    }

    public static void main(String[] args) {
        Code02_ArrayQueue queue = new Code02_ArrayQueue(10);
        for (int i = 1; i < 11; i++) {
            queue.offer(i);
        }
//        queue.offer(11);
        while (queue.getSize() != 0) {
            System.out.println(queue.poll());
        }
        queue.poll();
    }
}
